package com.yeyv.net.Security;

import com.alibaba.fastjson2.JSONObject;
import com.yeyv.net.UsefulEntity.RedisUtil;
import com.yeyv.net.UsefulEntity.Resp;
import com.yeyv.net.Web.Entity.AccountEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class LoginService {
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisUtil redisUtil;

    public Resp<String> login(AccountEntity loginUser) {
        UsernamePasswordAuthenticationToken authorToken = new UsernamePasswordAuthenticationToken(loginUser.getAccount(), loginUser.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authorToken);
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("登录失败");
        }
        var user = ((LoginUser) authenticate.getPrincipal()).getUserEntity();
        String redisKey = "UT-" + user.getUsername() + "-" + System.currentTimeMillis() + "-" + "RANDOM";
        if (!redisUtil.scan("UT-" + user.getUsername() + "*").isEmpty()) {
            redisUtil.delete("UT-" + user.getUsername() + "*");
        }
        JSONObject redisObj = new JSONObject();
        redisObj.put("user", authenticate.getPrincipal());
        redisUtil.set(redisKey, redisObj, 60 * 60 * 24);
        return Resp.success(redisKey);
    }
}
